package my.mvc;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import my.db.DBManager;

/**
 * 全局过滤器
 * @author Winter Lau
 * @date 2010-1-13 下午08:36:18
 */
public class ControllerFilter implements Filter {

	private ServletContext context;
	
	/**
	 * 过滤器初始化
	 */
	public void init(FilterConfig cfg) throws ServletException {
		this.context = cfg.getServletContext();
	}

	/**
	 * 执行过滤操作
	 */
	public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) 
		throws IOException, ServletException 
	{
		HttpServletRequest request = (HttpServletRequest)req;
		HttpServletResponse response = (HttpServletResponse)res;
		RequestContext rc = RequestContext.begin(this.context, request, response);
		
		if(rc.uri().indexOf("/.svn/")>=0){
			rc.forbidden();
			return ;
		}

		try{
			chain.doFilter(rc.request(), rc.response());
		}finally{
			if(rc!=null) rc.end();
			DBManager.closeConnection();
		}
	}

	/**
	 * 过滤器释放资源
	 */
	public void destroy() {
	}

}
